﻿using System.IO.Ports;
using NModbus;
using NModbus.Serial;

namespace MilkTeaMachine.OfflineClient.Utils;

public static class IModbusSerialFactory
{
    /// <summary>
    /// 默认波特率115200
    /// </summary>
    /// <param name="baudRate"></param>
    /// <param name="parity"></param>
    /// <returns></returns>
    public static IModbusSerialMaster Create(int baudRate = 115200, Parity parity = Parity.None)
    {
        var port = new SerialPort();
        port.StopBits = StopBits.One;
        var parser = new IniFileParser.IniFileParser();
        var data = parser.ReadFile("Configuration/config.ini");
        port.BaudRate = baudRate;
        port.Parity = parity;
        port.PortName = data["COM"]["port"];
        port.DataBits = int.Parse(data["COM"]["dataBits"]);
        if (!port.IsOpen)
            port.Open();
        var master = new ModbusFactory().CreateRtuMaster(port);
        return master;
    }
}